package com.mingzhi.forum.service.impl;

import com.mingzhi.forum.common.AppResult;
import com.mingzhi.forum.common.ResultCode;
import com.mingzhi.forum.dao.ArticleMapper;
import com.mingzhi.forum.exception.ApplicationException;
import com.mingzhi.forum.model.Article;
import com.mingzhi.forum.model.Board;
import com.mingzhi.forum.model.User;
import com.mingzhi.forum.service.IArticleService;
import com.mingzhi.forum.service.IBoardService;
import com.mingzhi.forum.service.IUserService;
import com.mingzhi.forum.utils.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private IUserService userService;

    @Resource
    private IBoardService boardService;

    //创建新帖
    @Override
    public void create(Article article) {
        //进行非空校验
        if (article == null
                || article.getUserId() == null
                || article.getBoardId() == null
                || StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //需要设置默认值
        article.setVisitCount(0);//访问量
        article.setReplyCount(0);//回复数
        article.setLikeCount(0);//点赞数
        article.setDeleteState((byte) 0);//状态
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        //写入数据库
        int articleRow = articleMapper.insertSelective(article);
        //进行判断
        if (articleRow <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //更新用户帖子数量
        User user = userService.selectById(article.getUserId());
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发帖失败，userid = " + article.getUserId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        userService.addOneArticleCountById(user.getId());
        //更新板块帖子数量
        Board board = boardService.selectById(article.getBoardId());
        if (board == null) {
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发帖失败，board id = " + article.getBoardId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        boardService.addOneArticleCountById(board.getId());

        //打印日志
        log.info(AppResult.success().toString()
                + "user id = " + user.getId()
                + "board id = " + board.getId()
                + "article id = " + article.getId() + "发帖成功");
    }

    @Override
    public List<Article> selectAll() {
        List<Article> articles = articleMapper.selectAll();
        return articles;
    }

    @Override
    public List<Article> selectByBoardId(Long boardId) {
        //对参数进行非空校验
        if (boardId == null || boardId <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //先进行单表查询进行校验 （因为单表查询的速度比联合查询的快）
        Board board = boardService.selectById(boardId);
        if (board == null) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + ", board id = " + boardId);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //真正的查询
        //调用mapper层
        List<Article> result = articleMapper.selectByBoardId(boardId);
        return result;
    }

    @Override
    public Article selectDetailById(Long id) {
        //对参数进行非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectDetailById(id);
        if (article == null) {
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //更新帖子的访问次数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        //更新到数据库
        int articleRow = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (articleRow != 1) {
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //返回帖子详情
        article.setVisitCount(article.getVisitCount() + 1);
        return article;
    }

    @Override
    public Article selectById(Long id) {
        //对参数进行非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        //对参数进行非空校验
        if (id == null || id <= 0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构建要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());//更新时间
        //调用mapper方法
        int articleRow = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (articleRow != 1) {
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void thumbsUpById(Long id) {
        //对参数进行非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据id查询帖子信息
        Article article = selectById(id);
        if (article == null || article.getDeleteState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //构造更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        //调用数据库
        int articleRow = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //进行校验
        if (articleRow != 1) {
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + ", userId = " + article.getUserId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
    }

    @Override
    public void deleteById(Long id) {
        //对参数进行非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据帖子id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null) {
            //打印日志 帖子不存在
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString() + ", article id = " + id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //构造一个更新后的帖子对象
        Article updateArticle = new Article();
        updateArticle.setId(id);//帖子id
        updateArticle.setDeleteState((byte) 1);//更新为1 表示删除
        //调用mapper对数据库处理
        int updateArticleRow = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (updateArticleRow != 1) {
            //打印日志
            log.warn(ResultCode.FAILED.toString() + ", 受影响行数不等于1 .");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //更新板块中帖子的数量
        boardService.subOneArticleCountById(article.getBoardId());
        //更新用户中帖子的数量
        userService.subOneArticleCountById(article.getUserId());

        //打印日志
        log.info("删除帖子成功，article id = " + article.getId() + ", board id = " + article.getBoardId() + ", user id = " + article.getUserId());
    }

    @Override
    public void addOneArticleReplyCountById(Long id) {
        //对参数进行非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据帖子id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        //
        if (article == null || article.getDeleteState() == 1) {
            //打印日志 帖子不存在
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString() + ", article id = " + id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        if (article.getState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //构造新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());//帖子id
        updateArticle.setReplyCount(article.getReplyCount() + 1);//回复数加一
        updateArticle.setUpdateTime(new Date());//更新时间
        //调用mapper写入数据库
        int updateArticleRow = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (updateArticleRow != 1) {
            //打印日志
            log.warn(ResultCode.FAILED.toString() + ", 受影响行数不等于1.");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //打印日志
        log.info("帖子回复数加一成功，articleid = " + article.getId() + ", board id = " + article.getBoardId() + ", user id = " + article.getUserId());
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //对参数进行非空校验
        if (userId == null || userId <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户是否存在
        User user = userService.selectById(userId);
        if(user == null || user.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", user id = " + userId);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //调用mapper层
        List<Article> result = articleMapper.selectByUserId(userId);
        return result;
    }
}
